// 获取微信步数
import request from '@/api/http.js'
import {
	api_version as api
} from '@/api/api.js'

function isEmpty(data, str) {
	// null ,undefined , '', []  = true
	if (data == null || data == undefined || data == '' || (typeof data == 'object' && Object.keys(data).length == 0)) {
		return true
	}
	// {} , {}[str] == null undefined ''  = true
	if (typeof data == 'object' && str != null || str != undefined) {
		if (data[str] == null || data[str] == undefined || data[str] == '') {
			return true
		}
	}
	// false
	return false
}



/**
 * 是否拥有某权限
 * @param {Object} permission 
 */
function hasPermission(permission) {
	return new Promise(resolve => {
		uni.getSetting({
			success(res) {
				if (res.authSetting[permission]) {
					resolve(true)
				} else {
					resolve(false)
				}
			}
		})
	})
}

/**
 * 无权限后获取权限
 * @param {Object} permission
 */
function getPermission(permission) {
	// 'scope.werun'
	return new Promise((resolve, reject) => {
		wx.authorize({
			scope: permission,
			success() {
				resolve()
			},
			fail(error) {
				reject(error)
			}
		})
	})
}

/**
 * 获取微信运动步数
 */
function getWXRunNumber() {
	return new Promise(resolve => {
		wx.getWeRunData({
			success(res) {
				const {
					encryptedData,
					iv
				} = res
				// console.log(encryptedData);
				// console.log(iv);
				request({
					...api.indexGetStep,
					data: {
						encryptedData,
						iv
					}
				}).then(response => {
					resolve(response)
				})
			}
		})
	})
}

/**
 * 获取 Code
 */
function getCode() {
	return new Promise(resolve => {
		uni.login({
			success(res) {
				if (res.code) {
					// console.log(res);
					resolve(res.code)
				} else {
					console.log('登录失败！' + res.errMsg)
					uni.showToast({
						title: '登录失败!',
						icon: 'none'
					})
				}
			},
			fail(err) {
				console.log(err);
			}
		})
	})
}



/**
 * 获取微信用户信息
 */
function getWXUserInfo() {
	return new Promise((resolve, reject) => {
		uni.getUserProfile({
			desc: "将获取您的头像昵称",
			lang: "zh_CN",
			success(infores) {
				request({
					...api.userupWechat,
					data: {
						avatar: infores.userInfo.avatarUrl,
						nickname: infores.userInfo.nickName,
					},
				}).then((res) => {
					resolve({
						...infores.userInfo,
						code: res.code
					})
				});
			},
			fail(err) {
				reject(err)
			},
		});
	})
}


/**
 * uni login 获取 token
 */
function loginToGetToken() {
	uni.showLoading({
		mask: true
	})
	//如果有token就不走接口，结束
	if (uni.getStorageSync('token')) return
	return new Promise((resolve, reject) => {
		getCode().then(res => {
			request(
				api.userLogin, {
					code: res
				}
			).then(res => { //有is_new和openid，token是空   （is_new 1是新用户）
				if (res.code == 0) {
					if (res.data.is_new != 1) { //老
						// uni.showToast({
						// 	title: '登录成功',
						// 	icon: "none"
						// })
						uni.switchTab({
							url: '/pages/index/index'
						})
						uni.setStorage({
							key: 'token',
							data: res.data.token,
						});
					} else { //新
						uni.setStorageSync('isNew', true)
						uni.showLoading({
							mask: true,
							title: '请绑定账号！',
							success() {
								setTimeout(() => {
									uni.reLaunch({
										url: '/pages/login/login'
									})
								}, 1500)
							}
						})
					}
					uni.setStorage({
						key: 'openid',
						data: res.data.openid,
					});
				} else {
					if (res.data.token) {
						uni.setStorageSync('token', res.data?.token)
					}
				}
				resolve(res)
			}).catch(apierror => {
				reject(apierror)
			})
		}).catch(error => {
			console.log('err', error);
			reject(error)
		})
	})
}

module.exports = {
	hasPermission,
	getWXRunNumber,
	getPermission,
	loginToGetToken,
	getCode,
	getWXUserInfo
}
